import React, { useState, useEffect, useRef } from 'react'
import { Table, Button, Space, Modal, Form, Input, theme } from 'antd'
import type { TableProps } from 'antd'
import { PageResult, TableColumn, PageParams } from '../types/component'
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons'

// 泛型表格属性接口
interface GenericTableProps<T> {
  // API配置
  api: {
    // 获取数据的函数
    fetch: (params: PageParams) => Promise<PageResult<T>>
    // 创建数据的函数（可选）
    create?: (data: Partial<T>) => Promise<T>
    // 更新数据的函数（可选）
    update?: (data: T) => Promise<T>
    // 删除数据的函数（可选）
    delete?: (id: any) => Promise<void>
  }
  
  // 列配置
  columns: TableColumn<T>[]
  
  // 表单字段配置
  formFields?: FormField<T>[]
  
  // 自定义事件
  onCreated?: (data: T) => void
  onUpdated?: (data: T) => void
  onDeleted?: (id: any) => void
  
  // 插槽
  slots?: {
    // 表格上方插槽
    tableHeader?: React.ReactNode
    // 表格下方插槽
    tableFooter?: React.ReactNode
    // 操作列插槽
    actionColumn?: (record: T) => React.ReactNode
    // 自定义操作按钮
    customActions?: (record: T) => React.ReactNode
  }
  
  // 其他配置
  config?: {
    // 是否显示新增按钮
    showCreateButton?: boolean
    // 是否显示操作列
    showActionColumn?: boolean
    // 表格标题
    title?: string
    // 是否启用分页
    pagination?: boolean
    // 默认分页参数
    defaultPageParams?: Partial<PageParams>
  }
}

// 表单字段配置类型
export interface FormField<T> {
  name: keyof T
  label: string
  type?: 'input' | 'textarea' | 'select' | 'number'
  required?: boolean
  rules?: any[]
  options?: { label: string; value: any }[]
  placeholder?: string
}

const GenericTable = <T extends { id?: any }>({
  api,
  columns,
  formFields = [],
  onCreated,
  onUpdated,
  onDeleted,
  slots,
  config = {}
}: GenericTableProps<T>) => {
  const { token } = theme.useToken()
  const [form] = Form.useForm()
  const [dataSource, setDataSource] = useState<PageResult<T>>({
    list: [],
    total: 0,
    page: 1,
    pageSize: config.defaultPageParams?.pageSize || 10
  })
  const [loading, setLoading] = useState(false)
  const [modalVisible, setModalVisible] = useState(false)
  const [modalTitle, setModalTitle] = useState('')
  const [editingRecord, setEditingRecord] = useState<T | null>(null)
  const pageParamsRef = useRef<PageParams>({
    page: 1,
    pageSize: config.defaultPageParams?.pageSize || 10,
    ...config.defaultPageParams
  })

  // 获取数据
  const fetchData = async (params?: Partial<PageParams>) => {
    setLoading(true)
    try {
      const finalParams = { ...pageParamsRef.current, ...params }
      pageParamsRef.current = finalParams
      const result = await api.fetch(finalParams)
      setDataSource(result)
    } catch (error) {
      console.error('获取数据失败:', error)
    } finally {
      setLoading(false)
    }
  }

  // 初始化数据
  useEffect(() => {
    fetchData()
  }, [])

  // 处理分页变化
  const handlePageChange = (page: number, pageSize?: number) => {
    fetchData({
      page,
      pageSize: pageSize || pageParamsRef.current.pageSize
    })
  }

  // 处理页面大小变化
  const handlePageSizeChange = (current: number, size: number) => {
    fetchData({
      page: 1,
      pageSize: size
    })
  }

  // 打开创建模态框
  const handleCreate = () => {
    if (!api.create) return
    setEditingRecord(null)
    setModalTitle('新增')
    form.resetFields()
    setModalVisible(true)
  }

  // 打开编辑模态框
  const handleEdit = (record: T) => {
    if (!api.update) return
    setEditingRecord(record)
    setModalTitle('编辑')
    form.setFieldsValue(record)
    setModalVisible(true)
  }

  // 处理删除
  const handleDelete = async (id: any) => {
    if (!api.delete) return
    try {
      await api.delete(id)
      if (onDeleted) onDeleted(id)
      // 重新加载数据
      fetchData()
    } catch (error) {
      console.error('删除失败:', error)
    }
  }

  // 处理表单提交
  const handleFinish = async (values: any) => {
    try {
      if (editingRecord && api.update) {
        // 编辑模式
        const updatedData = await api.update({ ...editingRecord, ...values })
        if (onUpdated) onUpdated(updatedData)
      } else if (api.create) {
        // 创建模式
        const newData = await api.create(values)
        if (onCreated) onCreated(newData)
      }
      setModalVisible(false)
      form.resetFields()
      // 重新加载数据
      fetchData()
    } catch (error) {
      console.error('保存失败:', error)
    }
  }

  // 生成表单字段
  const renderFormFields = () => {
    return formFields.map(field => {
      const { name, label, type = 'input', required = false, rules = [], options, placeholder } = field
      
      const commonProps = {
        name: name as string,
        label: <span style={{ 
          color: token.colorText,
          fontWeight: token.fontWeightStrong
        }}>{label}</span>,
        rules: required ? [...rules, { required: true, message: `请输入${label}` }] : rules,
        placeholder
      }
      
      switch (type) {
        case 'textarea':
          return (
            <Form.Item key={name as string} {...commonProps}>
              <Input.TextArea style={{ 
                backgroundColor: token.colorBgContainer,
                color: token.colorText,
                borderColor: token.colorBorder
              }} />
            </Form.Item>
          )
        case 'number':
          return (
            <Form.Item key={name as string} {...commonProps}>
              <Input type="number" style={{ 
                backgroundColor: token.colorBgContainer,
                color: token.colorText,
                borderColor: token.colorBorder
              }} />
            </Form.Item>
          )
        case 'select':
          return (
            <Form.Item key={name as string} {...commonProps}>
              {/* 简化处理，实际项目中可能需要使用 Select 组件 */}
              <Input style={{ 
                backgroundColor: token.colorBgContainer,
                color: token.colorText,
                borderColor: token.colorBorder
              }} />
            </Form.Item>
          )
        default:
          return (
            <Form.Item key={name as string} {...commonProps}>
              <Input style={{ 
                backgroundColor: token.colorBgContainer,
                color: token.colorText,
                borderColor: token.colorBorder
              }} />
            </Form.Item>
          )
      }
    })
  }

  // 添加操作列
  const actionColumn: TableColumn<T> = {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 150,
    render: (_, record) => (
      <Space size="middle">
        {slots?.actionColumn ? (
          slots.actionColumn(record)
        ) : (
          <>
            {api.update && (
              <Button 
                type="link" 
                icon={<EditOutlined />} 
                onClick={() => handleEdit(record)}
                style={{ 
                  padding: 0,
                  color: token.colorPrimary
                }}
              >
                编辑
              </Button>
            )}
            {api.delete && (
              <Button 
                type="link" 
                icon={<DeleteOutlined />} 
                onClick={() => handleDelete(record.id)}
                style={{ 
                  padding: 0,
                  color: token.colorError
                }}
                danger
              >
                删除
              </Button>
            )}
            {slots?.customActions && slots.customActions(record)}
          </>
        )}
      </Space>
    )
  }

  // 合并列配置
  const tableColumns = config.showActionColumn === false ? columns : [...columns, actionColumn]

  return (
    <div>
      {/* 表格上方插槽 */}
      {slots?.tableHeader}
      
      {/* 默认的新增按钮 */}
      {config.showCreateButton !== false && api.create && (
        <div style={{ marginBottom: 16 }}>
          <Button 
            type="primary" 
            icon={<PlusOutlined />} 
            onClick={handleCreate}
          >
            新增
          </Button>
        </div>
      )}
      
      <Table
        dataSource={dataSource.list}
        columns={tableColumns}
        loading={loading}
        rowKey="id"
        pagination={config.pagination === false ? false : {
          current: dataSource.page,
          pageSize: dataSource.pageSize,
          total: dataSource.total,
          onChange: handlePageChange,
          onShowSizeChange: handlePageSizeChange,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条记录`
        }}
        style={{
          backgroundColor: token.colorBgContainer,
          borderRadius: token.borderRadiusLG,
          color: token.colorText
        }}
      />
      
      {/* 表格下方插槽 */}
      {slots?.tableFooter}
      
      {/* 模态框 */}
      <Modal
        title={
          <div style={{ 
            color: token.colorText,
            fontSize: token.fontSizeLG,
            fontWeight: token.fontWeightStrong
          }}>
            {modalTitle}
          </div>
        }
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false)
          form.resetFields()
        }}
        onOk={() => form.submit()}
        width={600}
        styles={{
          body: {
            backgroundColor: token.colorBgContainer
          },
          header: {
            backgroundColor: token.colorBgContainer,
            borderBottom: `1px solid ${token.colorBorder}`
          },
          footer: {
            backgroundColor: token.colorBgContainer,
            borderTop: `1px solid ${token.colorBorder}`
          }
        }}
      >
        <Form
          form={form}
          onFinish={handleFinish}
          layout="vertical"
        >
          {renderFormFields()}
        </Form>
      </Modal>
    </div>
  )
}

export default GenericTable